/*
 * @Author: i@douxuefeng.cn
 * @Date: 2021-12-18 16:06:45
 * @LastEditTime: 2021-12-22 16:03:37
 * @LastEditors: i@douxuefeng.cn
 * @Description: 启动app
 * @FilePath: \go-im\app\start_app.go
 */

package app

import (
	"gitee.com/douxuefeng/go-im/router"
	"github.com/iris-contrib/middleware/cors"
	"github.com/kataras/iris/v12"
	"github.com/kataras/iris/v12/middleware/recover"
	"github.com/sirupsen/logrus"
	"github.com/spf13/viper"
)

func StartApp() {
	InitApp()
	app := newApp()
	router.InitRouter(app)
	app.Run(iris.Addr(viper.GetString("port")), iris.WithConfiguration(iris.Configuration{
		FireMethodNotAllowed: true,
		EnableOptimizations:  true,
		TimeFormat:           viper.GetString("timeFormat"),
		Charset:              "UTF-8",
	}))
}

func newApp() *iris.Application {
	app := iris.New()
	app.Use(recover.New())
	Cors := cors.New(cors.Options{
		AllowedOrigins:   []string{"*"},
		AllowedMethods:   []string{iris.MethodGet, iris.MethodPost, iris.MethodPut, iris.MethodDelete, iris.MethodOptions, iris.MethodPatch},
		AllowedHeaders:   []string{"*"},
		ExposedHeaders:   []string{"Accept", "Content-Type", "Content-Length", "Accept-Encoding", "X-CSRF-Token", "Authorization"},
		MaxAge:           3600,
		AllowCredentials: true,
	})
	app.UseRouter(Cors)

	app.OnAnyErrorCode(func(c iris.Context) {
		logrus.WithFields(logrus.Fields{
			"httpCode":  c.GetStatusCode(),
			"remote_ip": c.RemoteAddr(),
			"path":      c.Request().URL.RequestURI(),
			"method":    c.Method(),
			"agent":     c.Request().UserAgent(),
		}).Error()
	})
	return app
}
